package com.example.sse.service;

import com.example.sse.model.RealtimeData;
import com.example.sse.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * 数据生成服务
 * 模拟生成实时数据，用于演示SSE功能
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DataGeneratorService {

    private final ClusterCommunicationService clusterCommunicationService;
    private final Random random = new Random();

    /**
     * 模拟用户活动数据
     */
    private final List<String> userActivities = Arrays.asList(
        "用户登录", "用户注册", "查看商品", "添加购物车", "提交订单", "支付成功", "用户登出"
    );

    /**
     * 模拟订单状态
     */
    private final List<String> orderStatuses = Arrays.asList(
        "订单创建", "支付完成", "商品出库", "配送中", "已签收", "订单完成"
    );

    /**
     * 模拟城市列表
     */
    private final List<String> cities = Arrays.asList(
        "北京", "上海", "广州", "深圳", "杭州", "南京", "成都", "武汉", "西安", "重庆"
    );

    /**
     * 定时生成系统信息数据
     */
    @Scheduled(fixedRate = 10000) // 每10秒执行一次
    public void generateSystemInfo() {
        RealtimeData systemData = RealtimeData.builder()
            .id(UUID.randomUUID().toString())
            .type(RealtimeData.MessageType.SYSTEM_INFO.getCode())
            .content(MapUtils.of(
                "cpuUsage", random.nextInt(100) + "%",
                "memoryUsage", random.nextInt(100) + "%",
                "activeUsers", random.nextInt(1000) + 100,
                "todayOrders", random.nextInt(500) + 50,
                "serverTime", LocalDateTime.now().toString()
            ))
            .timestamp(LocalDateTime.now())
            .build();

        clusterCommunicationService.broadcastToCluster(systemData);
        log.debug("生成系统信息数据");
    }

    /**
     * 定时生成用户活动数据
     */
    @Scheduled(fixedRate = 5000) // 每5秒执行一次
    public void generateUserActivity() {
        String activity = userActivities.get(random.nextInt(userActivities.size()));
        String city = cities.get(random.nextInt(cities.size()));
        
        RealtimeData userData = RealtimeData.builder()
            .id(UUID.randomUUID().toString())
            .type(RealtimeData.MessageType.USER_ACTIVITY.getCode())
            .content(MapUtils.of(
                "userId", "user_" + (random.nextInt(9999) + 1000),
                "activity", activity,
                "city", city,
                "ip", generateRandomIP(),
                "timestamp", LocalDateTime.now().toString()
            ))
            .timestamp(LocalDateTime.now())
            .build();

        clusterCommunicationService.broadcastToCluster(userData);
        log.debug("生成用户活动数据: {}", activity);
    }

    /**
     * 定时生成订单更新数据
     */
    @Scheduled(fixedRate = 8000) // 每8秒执行一次
    public void generateOrderUpdate() {
        String status = orderStatuses.get(random.nextInt(orderStatuses.size()));
        
        RealtimeData orderData = RealtimeData.builder()
            .id(UUID.randomUUID().toString())
            .type(RealtimeData.MessageType.ORDER_UPDATE.getCode())
            .content(MapUtils.of(
                "orderId", "ORD" + System.currentTimeMillis(),
                "status", status,
                "amount", (random.nextInt(50000) + 1000) / 100.0,
                "customerName", "客户_" + (random.nextInt(999) + 100),
                "updateTime", LocalDateTime.now().toString()
            ))
            .timestamp(LocalDateTime.now())
            .build();

        clusterCommunicationService.broadcastToCluster(orderData);
        log.debug("生成订单更新数据: {}", status);
    }

    /**
     * 定时生成支付通知数据
     */
    @Scheduled(fixedRate = 12000) // 每12秒执行一次
    public void generatePaymentNotify() {
        boolean success = random.nextBoolean();
        
        RealtimeData paymentData = RealtimeData.builder()
            .id(UUID.randomUUID().toString())
            .type(RealtimeData.MessageType.PAYMENT_NOTIFY.getCode())
            .content(MapUtils.of(
                "paymentId", "PAY" + System.currentTimeMillis(),
                "orderId", "ORD" + (System.currentTimeMillis() - random.nextInt(3600000)),
                "amount", (random.nextInt(100000) + 500) / 100.0,
                "status", success ? "success" : "failed",
                "paymentMethod", random.nextBoolean() ? "微信支付" : "支付宝",
                "message", success ? "支付成功" : "支付失败",
                "payTime", LocalDateTime.now().toString()
            ))
            .timestamp(LocalDateTime.now())
            .build();

        clusterCommunicationService.broadcastToCluster(paymentData);
        log.debug("生成支付通知数据: {}", success ? "成功" : "失败");
    }

    /**
     * 手动触发数据生成（用于API调用）
     * @param type 数据类型
     * @param content 自定义内容
     */
    public void generateCustomData(String type, Object content) {
        RealtimeData customData = RealtimeData.builder()
            .id(UUID.randomUUID().toString())
            .type(type)
            .content(content)
            .timestamp(LocalDateTime.now())
            .build();

        clusterCommunicationService.broadcastToCluster(customData);
        log.info("生成自定义数据: {}", type);
    }

    /**
     * 生成随机IP地址
     * @return IP地址
     */
    private String generateRandomIP() {
        return String.format("%d.%d.%d.%d",
            random.nextInt(255) + 1,
            random.nextInt(255),
            random.nextInt(255),
            random.nextInt(255)
        );
    }
}